<?php
// 数据库配置文件
require_once 'database.php';

// 全局配置
define('SITE_NAME', '考务管理系统');
define('SITE_VERSION', '1.0.0');
define('DEBUG_MODE', false);

// 时区设置
date_default_timezone_set('Asia/Shanghai');

// 错误报告设置
if (DEBUG_MODE) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
}

// 会话配置
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
ini_set('session.cookie_secure', 0); // 如果使用HTTPS，设置为1

// 安全配置
ini_set('session.cookie_samesite', 'Strict');

// 全局函数
function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verify_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// 日志函数
function log_activity($user_id, $action, $details = '') {
    $log_entry = date('Y-m-d H:i:s') . " - User: $user_id - Action: $action";
    if ($details) {
        $log_entry .= " - Details: $details";
    }
    $log_entry .= PHP_EOL;

    $log_file = __DIR__ . '/../logs/activity.log';
    $log_dir = dirname($log_file);

    if (!is_dir($log_dir)) {
        mkdir($log_dir, 0755, true);
    }

    file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
}

// 权限检查函数
function check_permission($required_role) {
    global $conn;

    if (!isset($_SESSION['user_id'])) {
        return false;
    }

    $user_id = $_SESSION['user_id'];

    // 检查user_roles表是否存在
    try {
        $check_table = $conn->query("SHOW TABLES LIKE 'user_roles'");
        if (!$check_table || $check_table->num_rows == 0) {
            return false;
        }

        // 系统管理员拥有所有权限
        $admin_sql = "SELECT COUNT(*) as count FROM user_roles WHERE user_id = ? AND role = '系统管理员'";
        $admin_stmt = $conn->prepare($admin_sql);
        $admin_stmt->bind_param('s', $user_id);
        $admin_stmt->execute();
        $admin_result = $admin_stmt->get_result();
        $admin_row = $admin_result->fetch_assoc();

        if ($admin_row['count'] > 0) {
            return true;
        }

        // 检查特定权限
        $role_sql = "SELECT COUNT(*) as count FROM user_roles WHERE user_id = ? AND role = ?";
        $role_stmt = $conn->prepare($role_sql);
        $role_stmt->bind_param('ss', $user_id, $required_role);
        $role_stmt->execute();
        $role_result = $role_stmt->get_result();
        $role_row = $role_result->fetch_assoc();

        return $role_row['count'] > 0;

    } catch (Exception $e) {
        error_log("权限检查错误: " . $e->getMessage());
        return false;
    }
}

// 获取用户角色
function get_user_roles($user_id) {
    global $conn;
    $roles = [];

    try {
        $check_table = $conn->query("SHOW TABLES LIKE 'user_roles'");
        if ($check_table && $check_table->num_rows > 0) {
            $sql = "SELECT role FROM user_roles WHERE user_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('s', $user_id);
            $stmt->execute();
            $result = $stmt->get_result();

            while ($row = $result->fetch_assoc()) {
                $roles[] = $row['role'];
            }
        }
    } catch (Exception $e) {
        error_log("获取用户角色错误: " . $e->getMessage());
    }

    return empty($roles) ? ['普通账号'] : $roles;
}

// 格式化日期
function format_date($date, $format = 'Y-m-d H:i:s') {
    if (empty($date) || $date == '0000-00-00 00:00:00') {
        return '未设置';
    }
    return date($format, strtotime($date));
}

// 分页函数
function paginate($total_records, $records_per_page, $current_page) {
    $total_pages = ceil($total_records / $records_per_page);
    $offset = ($current_page - 1) * $records_per_page;

    return [
        'total_pages' => $total_pages,
        'current_page' => $current_page,
        'offset' => $offset,
        'limit' => $records_per_page,
        'has_prev' => $current_page > 1,
        'has_next' => $current_page < $total_pages,
        'prev_page' => $current_page > 1 ? $current_page - 1 : null,
        'next_page' => $current_page < $total_pages ? $current_page + 1 : null
    ];
}

// 响应JSON
function json_response($data, $status_code = 200) {
    http_response_code($status_code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 重定向函数
function redirect($url, $message = null, $type = 'info') {
    if ($message) {
        $_SESSION['flash_message'] = $message;
        $_SESSION['flash_type'] = $type;
    }
    header("Location: $url");
    exit;
}

// 获取Flash消息
function get_flash_message() {
    if (isset($_SESSION['flash_message'])) {
        $message = $_SESSION['flash_message'];
        $type = $_SESSION['flash_type'] ?? 'info';
        unset($_SESSION['flash_message'], $_SESSION['flash_type']);
        return ['message' => $message, 'type' => $type];
    }
    return null;
}
?>